<template>
  <u-popup
    v-model="modalVisible"
    mode="bottom"
    :mask-close-able="false"
    @close="popupCloseCb"
  >
    <view class="panel-content">
      <view class="panel-header am-flex-rc-center">
        订单金额合计：
        <text class="panel-header__price-num">￥{{ totalPrice }}</text>
        <view class="panel-header__close" @click="closePopup"
          ><u-icon name="close" color="#999" size="32rpx"></u-icon
        ></view>
      </view>
      <view class="panel-bd">
        <scroll-view scroll-y="true" class="panel-bd-scroll">
          <view>
            <view class="am-flex-rc-center loading-wrap" v-show="getType === 1">
              <u-loading mode="circle" color="#FE6507"></u-loading>
              <text class="loading-text">加载中</text>
            </view>
            <view class="am-flex-rc-between retry-wrap" v-show="getType === 3"
              ><button
                class="u-reset-button co-success-button retry-button"
                @click="getData"
              >
                重试
              </button></view
            >
            <view
              class="supplier-list"
              v-for="(item, index) in orderData"
              :key="index"
            >
              <view class="supplier-name am-text-eill">{{
                item.supplier
              }}</view>
              <view class="am-flex-rc-between oder-price-item">
                <view class="p-label">订单金额</view>
                <view class="p-value"
                  >{{ item.payType == 'points' ? '' : '￥'
                  }}{{ item.orderPrice }}</view
                >
              </view>
              <view class="am-flex-rc-between cur-supplier-balance">
                <view class="p-label"
                  >当前账户{{ textHandle(item.payType) }}余额</view
                >
                <view
                  class="p-value"
                  :class="{ 'not-enough': item.balance < item.orderPrice }"
                  >{{ item.payType == 'points' ? '' : '￥'
                  }}{{ item.balance }}</view
                >
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="panel-ft am-flex-rc-between">
        <button
          class="u-reset-button co-primary-button pay-button"
          hover-class="co-primary-button--hover"
          :disabled="getType !== 2"
          :loading="payIsLoading"
          @click="payHandle"
        >
          立即付款
        </button>
      </view>
    </view>
  </u-popup>
</template>

<script>
import { apiOrderBalance, apiOrderToPay } from '@/api/order'
import Big from 'big.js'
// 0: "1454306459939504128"
// 1: "1454306460207939584"

// 支付失败:因为用户余额不足，系统主动终止支付
const notEnoughStop = 'not_enough_stop'
export default {
  name: 'pay-panel',
  props: {
    /**
     * 支付场景
     * cart 购物车下单支付场景
     * goods 商品下单支付场景
     * order 订单列、详情支付场景
     * */
    scene: {
      type: String,
      default: () => 'cart'
    }
  },
  data() {
    return {
      modalVisible: false,
      orderData: [],
      orderIdArr: [],
      payIsLoading: false,
      getType: 999, // 请求状态； 1 请求中 ；2 请求成功；  3 请求失败
      payType: ''
    }
  },
  computed: {
    totalPrice() {
      let total = new Big(0)
      this.orderData.forEach((p1) => {
        total = total.plus(p1.orderPrice)
      })
      return Number(total)
    }
  },
  created() {
    // this.pay_out(['1454306459939504128-33']);
  },
  methods: {
    textHandle(t) {
      let cusObj = {
        cashBack: '返现金',
        incentive: '奖励金',
        points: '积分',
        balance: '充值'
      }
      return cusObj[t]
    },
    /**
     * 暴露外边使用
     * @param {Array} orderIdArr - 订单oid 集合
     * */
    pay_out(orderIdArr, orderData) {
      this.orderIdArr = orderIdArr
      this.payType = orderData[0].payType
      this.getType = 999
      this.modalVisible = true
      if (orderData) {
        this.orderData = orderData
        this.getType = 2
      } else {
        this.getData()
      }
    },
    getData() {
      if (this.getType === 1) {
        return
      }
      this.getType = 1
      apiOrderBalance(this.orderIdArr)
        .then((res) => {
          let { state, data, msg } = res.data
          if (state === 'OK') {
            console.log(data)
            this.orderData = data
            this.getType = 2
          } else {
            this.getType = 3
            this.$am_toast.warning(msg)
          }
        })
        .catch(() => {
          this.getType = 3
          this.$am_toast.warning('余额信息查询失败！')
        })
    },
    closePopup() {
      uni.showModal({
        title: '放弃付款',
        content: '是否放弃本次付款？',
        confirmColor: '#4BB019',
        success: (cancelRes) => {
          if (cancelRes.confirm) {
            this.modalVisible = false
            // 用户放弃付款
            this.$emit('payFail', {
              type: 'user_cancel',
              orderIds: this.orderIdArr
            })
          }
        }
      })
    },
    // 点击立即付款
    payHandle() {
      if (this.getType !== 2) {
        // 供应商查询没有成功
        return
      }
      if (this.payIsLoading) return
      if (this.orderData[0].orderPrice > this.orderData[0].balance) {
        uni.showModal({
          content: `余额不足，请联系管理员充值`,
          confirmColor: '#4BB019',
          confirmText: '确定',
          showCancel: false,
          success: (confirmRes) => {}
        })
      } else {
        uni.showModal({
          content: '确认支付本次订单付款？',
          confirmColor: '#4BB019',
          success: (confirmRes) => {
            if (confirmRes.confirm) {
              this.payOrder()
            }
          }
        })
      }
      // let notEnough = this.orderData.filter(p1 => p1.orderPrice > p1.balance);
      // if (notEnough.length !== 0) {
      // this.$emit('payFail', { type: notEnoughStop, msg: '余额不足，请联系管理员充值'});
      // 有钱不够的
      // if (this.scene === 'cart') {
      // 	uni.showModal({
      // 		content: `当前有${notEnough.length}个公司余额不足，请联系管理员充值 \r\n 是否继续下单？`,
      // 		confirmColor: '#4BB019',
      // 		confirmText: '继续付款',
      // 		success: confirmRes => {
      // 			if (confirmRes.confirm) {
      // 				this.payOrder();
      // 			}
      // 		}
      // 	});
      // } else if (this.scene === 'goods') {
      // 	uni.showModal({
      // 		content: `当前公司余额不足，请联系管理员充值 \r\n 充值后请立即支付`,
      // 		confirmColor: '#4BB019',
      // 		confirmText: '确定',
      // 		showCancel: false,
      // 		success: confirmRes => {
      // 			// 用户点了物理返回键，会进入cancel.所以这里认定有操作即为取消
      // 			this.$emit('payFail', { type: notEnoughStop, msg: '当前公司余额不足，请联系管理员充值', orderIds: this.orderIdArr, scene: this.scene });
      // 		}
      // 	});
      // } else if (this.scene === 'order') {
      // 	this.modalVisible = false;
      // 	this.$emit('payFail', { type: notEnoughStop, msg: '余额不足，请联系管理员充值', orderIds: this.orderIdArr, scene: this.scene });
      // }
      // } else {
      // 	// 钱都够
      // 	uni.showModal({
      // 		content: '确认支付本次订单付款？',
      // 		confirmColor: '#4BB019',
      // 		success: confirmRes => {
      // 			if (confirmRes.confirm) {
      // 				this.payOrder();
      // 			}
      // 		}
      // 	});
      // }
    },
    // 立即付款
    payOrder() {
      if (this.payIsLoading) return
      this.payIsLoading = true
      uni.showLoading({
        mask: true,
        title: '支付中'
      })
      console.log(this.orderIdArr)
      let params = {
        oidList: this.orderIdArr,
        paymentType: this.payType
      }
      apiOrderToPay(params)
        .then((res) => {
          let { state, data, msg } = res.data
          uni.hideLoading()
          if (state === 'OK') {
            this.$emit('paySuccess')
          } else {
            this.$emit('payFail', {
              type: 'pay_fail',
              msg: msg,
              orderIds: this.orderIdArr,
              scene: this.scene
            })
            this.$am_toast.warning(msg)
          }
          this.modalVisible = false
          this.payIsLoading = false
        })
        .catch(() => {
          uni.hideLoading()
          this.modalVisible = false
          this.$emit('payFail', {
            type: 'pay_error',
            orderIds: this.orderIdArr,
            scene: this.scene
          })
          this.payIsLoading = false
          this.$am_toast.warning('付款失败！')
        })
    },
    popupCloseCb() {
      this.orderData = []
      this.orderIdArr = []
      this.getType = 999
    }
  }
}
</script>

<style lang="scss" scoped>
$section-plr: 55rpx;
.panel-content {
  background-color: #fff;
}
.panel-header {
  position: relative;
  height: 121rpx;
  font-size: 34rpx;
  color: #000000;
}
.panel-header__price-num {
  color: #f65301;
}
.panel-header__close {
  position: absolute;
  z-index: 15;
  top: 0;
  right: 0;
  padding: 15rpx;
}
.panel-bd {
}

.panel-bd-scroll {
  height: 490rpx;
}
.supplier-list {
  padding: 29rpx 0;
  & + .supplier-list {
    border-top: 1px solid #e8e8e8;
  }
}
.supplier-name {
  padding: 0 $section-plr;
  font-size: 24rpx;
  color: #000;
}
.oder-price-item {
  margin-top: 40rpx;
  padding: 0 $section-plr;
  font-size: 30rpx;
  .p-label {
    color: #000;
  }
  .p-value {
    color: #333;
  }
}
.cur-supplier-balance {
  margin-top: 40rpx;
  padding: 0 $section-plr;
  .p-label {
    font-size: 24rpx;
    color: #666;
  }
  .p-value {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
    &.not-enough {
      color: red;
    }
  }
}
.panel-ft {
  height: 138rpx;
  border-top: 1px solid #e8e8e8;
}
.pay-button {
  height: 80rpx;
  width: 690rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 34rpx;
}
.loading-wrap {
  height: 200rpx;
}
.loading-text {
  padding-left: 15rpx;
  color: #666;
}
.retry-wrap {
  height: 200rpx;
}
.retry-button {
  width: 350rpx;
}
</style>
